package com.d3works.apps.account.db.repo;

import com.d3works.apps.account.db.Account;
import com.d3works.apps.account.exception.AccountExceptionMessage;
import com.d3works.db.JPA;
import com.d3works.exception.D3worksException;
import com.d3works.exception.db.repo.TraceBackRepository;
import com.d3works.exception.service.TraceBackService;
import com.d3works.i18n.I18n;
import java.util.Set;
import javax.persistence.PersistenceException;

public class AccountAccountRepository extends AccountRepository {

  @Override
  public Account save(Account account) {
    try {
      if (account.getId() == null) {
        return super.save(account);
      }

      if (account.getReconcileOk()) {
        Set<Account> accountList = account.getCompatibleAccountSet();

        if (accountList != null) {
          for (Account acc : accountList) {
            acc.setReconcileOk(true);
            acc.addCompatibleAccountSetItem(account);
            JPA.save(acc);
          }
        }
      } else {

        if (account.getCompatibleAccountSet() != null) {
          for (Account acc : account.getCompatibleAccountSet()) {
            acc.removeCompatibleAccountSetItem(account);
            if (acc.getCompatibleAccountSet().size() == 0) {
              acc.setReconcileOk(false);
            }
            JPA.save(acc);
          }
          account.getCompatibleAccountSet().clear();
        }
      }
      return super.save(account);
    } catch (Exception e) {
      TraceBackService.traceExceptionFromSaveMethod(e);
      throw new PersistenceException(e.getMessage(), e);
    }
  }

  @Override
  public Account copy(Account entity, boolean deep) {
    Account account = super.copy(entity, deep);
    account.setCode(String.format("%s (copy)", account.getCode()));
    account.setName(String.format("%s (copy)", account.getName()));
    account.setStatusSelect(AccountRepository.STATUS_INACTIVE);
    return account;
  }

  @Override
  public void remove(Account account) {
    if (account.getIsRegulatoryAccount()) {
      Exception e =
          new D3worksException(
              TraceBackRepository.CATEGORY_INCONSISTENCY,
              I18n.get(AccountExceptionMessage.ACCOUNT_REGULATORY_REMOVE));
      TraceBackService.traceExceptionFromSaveMethod(e);
      throw new PersistenceException(e);
    }
    super.remove(account);
  }
}
